package cn.edu.wdu.gaojie.jdbc;

import java.sql.*;
import java.util.Scanner;

/**
 * @author gaojie  gao4433@qq.com
 * @Description 模拟用户登录
 * @date 2021/12/2 15:58
 * @since 1.8
 */
public class AppLogin {
    public static void main(String[] args) throws Exception {
        System.out.println("请输入账号：");
        Scanner scanner = new Scanner(System.in);
        String username = scanner.nextLine();
        System.out.println("请输入密码：");
        String password = scanner.nextLine();

        //Login(username, password);
        LoginPlus(username,password);

    }

    public static void Login(String u, String p) throws Exception {
        System.out.println("username= " + u);
        System.out.println("password= " + p);

        String sql = "SELECT id FROM `user` WHERE username = '" + u +
                "' AND `password` = MD5('" + p +
                "')";
        System.out.println("组成的 sql 语句是：%d" + sql);

        Class.forName("com.mysql.jdbc.Driver");

        String url = "jdbc:mysql://localhost:3306/test?useSSL=false";
        String username = "root";
        String password = "778874315";
        Connection connection = DriverManager.getConnection(url, username, password);

        Statement statement = connection.createStatement();

        ResultSet set = statement.executeQuery(sql);
        //如果数据库查到了与用户名和密码对应的结果，set 中最少有一条数据
        //使用 next() 方法后光标移动到第一行数据，会返回 true
        if (set.next()) {
            System.out.println("登录成功！");
        } else { //当 set 中没有数据时，使用 next() 方法就会返回 false
            System.out.println("登录失败！");
        }


    }

    public static void LoginPlus(String u, String p) throws SQLException, ClassNotFoundException {
        System.out.println("username= " + u);
        System.out.println("password= " + p);

        String sql = "SELECT id FROM `user` WHERE username = ? AND `password` = MD5(?)";
        System.out.println("组成的 sql 语句是：%d" + sql);

        Class.forName("com.mysql.jdbc.Driver");

        String url = "jdbc:mysql://localhost:3306/test?useSSL=false";
        String username = "root";
        String password = "778874315";
        Connection connection = DriverManager.getConnection(url, username, password);

        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,u);
        ps.setString(2,p);
        ResultSet set = ps.executeQuery();

        if (set.next()){
            System.out.println("登录成功！");
        } else {
            System.out.println("登录失败！");
        }
    }
}
